<?php

namespace app\common\model;

use think\Db;

class ShopCardModel extends BaseModel
{

    protected $name = 'shop_card'; //定义栏目表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = false;
    // 定义自动完成的属性
    protected $auto = []; //新增修改
    protected $insert = []; //插入
    protected $update = []; //修改
    protected $type = ['begin_timestamp' => 'timestamp', 'end_timestamp' => 'timestamp'];//类型管理

    protected function getBeginDateAttr($value, $data)
    {
        if ($data['date_type'] == 'DATE_TYPE_FIX_TIME_RANGE') {
            return date('Y-m-d H:i:s', $data['begin_timestamp']);
        }
        if ($data['date_type'] == 'DATE_TYPE_FIX_TERM') {
            return date('Y-m-d H:i:s', (time() + $data['fixed_begin_term'] * 60 * 60 * 24));
        }
    }

    protected function getEndDateAttr($value, $data)
    {
        if ($data['date_type'] == 'DATE_TYPE_FIX_TIME_RANGE') {
            return date('Y-m-d H:i:s', $data['end_timestamp']);
        }
        if ($data['date_type'] == 'DATE_TYPE_FIX_TERM') {
            return date('Y-m-d H:i:s', time() + ($data['fixed_begin_term'] + $data['fixed_term']) * 60 * 60 * 24);
        }
    }

    protected function getSendTypeTextAttr($value, $data)
    {
        $arr = [0 => '线上发放', 1 => '线下发放', 2 => '在线购买'];
        return $arr[$data['send_type']];
    }

    /**
     * 卡券分页
     * @param int $status 1可用，其他全部
     * @param array $map 筛选条件
     * @param array $query 附加条件
     * @return \think\Paginator
     */
    public function getPageList($status, $map=[], $query=[])
    {
        $time = time();
        if ($status == 1) { //可使用优惠券
            $list = $this->where("case quantity
                    when 0 then quantity=0
                    else quantity>0 and quantity>receive_num
                end")
                ->where("case date_type
                    when 'DATE_TYPE_FIX_TIME_RANGE' then end_timestamp>={$time}
                    else 1=1
                end")
                ->where($map)
                ->order('card_id desc')
                ->paginate(24, false, ['query' => $query]);
        } else {
            $list = $this
                ->where("case quantity
                    when 0 then quantity=0
                    else quantity>0 and quantity<=receive_num
                end")
                ->whereOr("case date_type
                    when 'DATE_TYPE_FIX_TIME_RANGE' then end_timestamp<{$time}
                end")
                ->where($map)
                ->order('card_id desc')
                ->paginate(24, false, ['query' => $query]);
        }
        return $list;
    }


    /**
     * 删除卡券
     * @param $cardId
     * @return bool
     */
    public function delData($cardId)
    {
        $map['card_id']    = $cardId;
        $map['member_uid'] = ['>', 0];
        $itemInfo          = Db::table('shop_card_item')->where($map)->find();
        if ($itemInfo) {
            $this->error = '该卡券已有会员领取，不允许删除！';
            return false;
        }
        $map            = [];
        $map['card_id'] = $cardId;
        Db::table('shop_card')->where($map)->delete();
        Db::table('shop_card_item')->where($map)->delete();
        return true;
    }

    /**
     * 发放卡券
     * @param $uid
     * @param $cardId
     * @return bool
     */
    public function sendCard($uid, $cardId)
    {
        $cardItemModel       = new ShopCardItemModel();
        $d_map['card_id']    = $cardId;
        $cardInfo            = $this->where($d_map)->find(); //卡券信息
        $i_map['card_id']    = $cardId;
        $i_map['member_uid'] = ['gt', 0];
        $receiveNum          = $cardItemModel->where($i_map)->count(); //已领取数量
        if ($cardInfo['quantity'] > $receiveNum || $receiveNum['quantity'] == 0) {
            $c_map['card_id']    = $cardId;
            $c_map['member_uid'] = $uid;
            if ($cardItemModel->where($c_map)->find()) {
                $this->error = '每人只能领取一次卡券';
                return false;
            } else {
                $cardKey = $cardItemModel->getCardKey();
                $data    = [
                    'card_id'      => $cardId,
                    'card_key'     => $cardKey,
                    'member_uid'   => $uid,
                    'receive_time' => time(),
                    'status'=>$cardInfo['send_type']==2?0:1
                ];
                $cardItemModel->addData($data);
                $map['card_id'] = $cardId;
                $this->where($map)->setInc('receive_num', 1);//领取数量+1
            }
            return $cardItemModel->getData('item_id');
        } else {
            $this->error = '库存数量不足';
            return false;
        }
    }

    /**
     * 获取卡券信息
     * @param $cardKey
     * @return array|bool|false|\PDOStatement|string|\think\Model
     */
    public function getCardInfo($cardKey)
    {
        $time            = time();
        $map['card_key'] = $cardKey;
        $cardInfo        = $this->alias('t1')
            ->join("shop_card_item t2", "t1.card_id=t2.card_id")
            ->where($map)->find();
        if ($cardInfo) {
            $cardInfo = $cardInfo->append(['begin_date', 'end_date'])->toArray();
            if ($cardInfo['is_use'] == 1) {
                $this->error = '该卡券已使用！';
                return false;
            }
            if (strtotime($cardInfo['begin_date']) < $time && strtotime($cardInfo['end_date']) > $time) {
                return $cardInfo;
            } else {
                $this->error = '该卡券不在有效期内!';
                return false;
            }
        } else {
            $this->error = '没有该卡券';
            return false;
        }
    }

    /**
     * 计算卡券金额
     * @param $cardKey
     * @param int $orderMoney
     * @return bool|mixed
     */
    public function getCardPrice($cardKey, $orderPrice = 0)
    {
        $cardInfo = $this->getCardInfo($cardKey);
        if ($cardInfo) {
            if ($orderPrice >= $cardInfo['order_money']) {
                $cardMoney = $cardInfo['card_money'];
                return $cardMoney;
            } else {
                $this->error = '该卡券不满足优惠条件！';
                return 0;
            }
        } else {
            return 0;
        }
    }

    /**
     * 核销卡券
     * @param $cardKey
     * @param $orderId
     * @param $orderMoney
     * @param $cardMoney
     * @return bool
     */
    public function useCard($cardKey, $orderId, $orderMoney, $cardMoney)
    {
        $cardItemModel   = new ShopCardItemModel();
        $map['card_key'] = $cardKey;
        $map['is_use']   = 0;
        $cardInfo        = $cardItemModel->where($map)->find();
        if ($cardInfo) {
            $data = [
                'is_use'         => 1,
                'order_id'       => $orderId,
                'order_money'    => $orderMoney,
                'use_card_money' => $cardMoney,
                'use_time'       => time(),
            ];
            $cardItemModel->where($map)->update($data);
            $map=[];
            $map['card_id'] = $cardInfo['card_id'];
            $this->where($map)->setInc('use_num', 1);//使用数量+1
            return true;
        } else {
            $this->error = '未找到有效卡券！';
            return false;
        }
    }

    /**
     * 还原卡券
     * @param $cardKey
     */
    public function returnCard($cardKey){
        $cardItemModel   = new ShopCardItemModel();
        $map['card_key'] = $cardKey;
        $cardInfo        = $cardItemModel->where($map)->find();
        $data = [
            'is_use'         => 0,
            'order_id'       => 0,
            'order_money'    => 0,
            'use_card_money' => 0,
            'use_time'       => 0,
        ];
        $cardItemModel->where($map)->update($data); //还原卡券
        $this->where('card_id',$cardInfo['card_id'])->setDec('use_num', 1);//使用数量-1
        return true;
    }

}